import type { DefineLocaleMessage } from 'vue-i18n'
import { merge, set } from 'lodash-es'
import { nextTick, unref } from 'vue'
import { langs as apiLangs } from '@/apis/common'
import { i18n } from '.'

/**
 * 获取语言包并和本地语言包合并
 * @param lang 语言标识
 * @returns 合并后的语言包
 */
async function getLangRes(lang: string): Promise<DefineLocaleMessage> {
  try {
    const localeLang = await import(`./langs/${lang}/index.ts`)
    // 接口返回语言包
    const apiLang = await apiLangs()
    // const apiLang = {}
    return merge(localeLang.default ?? {}, apiLang)
  }
  catch (error) {
    console.error(`Failed to load language ${lang}:`, error)
    return {}
  }
}

/**
 * 改变语言
 * @param lang 语言标识
 */
export async function changeLocale(lang: string) {
  const currentLocale = unref(i18n.global.locale)
  if (currentLocale === lang) {
    return
  }
  if (!i18n.global.availableLocales.includes(lang)) {
    const langs = await getLangRes(lang)
    i18n.global.setLocaleMessage(lang, langs)
  }
  document?.querySelector('html')?.setAttribute('lang', lang)
  i18n.global.locale.value = lang
  await nextTick()
}

/**
 * 递归文件下的所有json文件里的内容并组合成对象
 * @param langs 语言文件
 */
export function genMessage(langs: Recordable<Recordable>) {
  const obj: Recordable = {}
  Object.keys(langs).forEach((key) => {
    const langFileModule = langs[key].default

    let fileName = key
      .replace(/^\.\//, '')

    const lastIndex = fileName.lastIndexOf('.')
    fileName = fileName.substring(0, lastIndex)
    const keyList = fileName.split('/')
    const moduleName = keyList.shift()
    const objKey = keyList.join('.')

    if (moduleName) {
      if (objKey) {
        set(obj, moduleName, obj[moduleName] || {})
        set(obj[moduleName] as object, objKey, langFileModule)
      }
      else {
        set(obj, moduleName, langFileModule || {})
      }
    }
  })
  return obj
}
